<template>
  <div class="main">
    <button @click="export2Excel">导出EXCEL</button>
    <CartSubject
      v-for="(item, index) in cart"
      :key="index"
      :index="index+1"
      :title="item.title"
      :data="item.data"
    ></CartSubject>
  </div>
</template>

<script>
import CartSubject from "../components/CartSubject";
import { createNamespacedHelpers } from "vuex";
let { mapMutations, mapState, mapGetters } = createNamespacedHelpers("subject");
import {export_json_to_excel} from '@/utils/Export2Excel'
export default {
  components: {
    CartSubject
  },
  data() {
    return {
      cart: []
    };
  },
  watch: {
    subjectCartList(){
       this.initSubjectCart()
    }
  },
  mounted() {
    this.initSubjectCart()
  },
  computed: {
    ...mapState(["subjectCartList"]),
    ...mapGetters([
      "cartCount",
      "cart_danxuanlist",
      "cart_duoxuanlist",
      "cart_panduanlist",
      "cart_jiandalist"
    ])
  },
  methods: {
    ...mapMutations(["setSubjectList", "add2Cart", "removeFromCart"]),
    initSubjectCart() {
      this.cart = []
      if (this.checkArrayHasVal(this.cart_danxuanlist)) {
        this.cart.push({
          title: "单选题",
          data: this.cart_danxuanlist || []
        });
      }
      if (this.checkArrayHasVal(this.cart_duoxuanlist)) {
        this.cart.push({
          title: "多选题",
          data: this.cart_duoxuanlist || []
        });
      }
      if (this.checkArrayHasVal(this.cart_panduanlist)) {
        this.cart.push({
          title: "判断题",
          data: this.cart_panduanlist || []
        });
      }
      if (this.checkArrayHasVal(this.cart_jiandalist)) {
        this.cart.push({
          title: "简答题",
          data: this.cart_jiandalist || []
        });
      }
    },
    fmtOptions(arr){
      if (!arr) {
        return ''
      }
      return arr.map(r=>r.val).join('|')
    },
    export2Excel(){
      let data = []
      this.cart.forEach(r => {
        r.data.forEach(s=>{
          data.push([r.title,s.name,this.fmtOptions(s.options),s.answer,s.desc])
        })
        
      });
      
      export_json_to_excel({
        header:["题型","题目","选项",'答案','解析'],
        data,
        filename:"题目"+new Date().toLocaleDateString()
      })  
    }
  }
};
</script>

<style lang="scss">
$c: black;
.main {
  width: 500px;
  margin: 100px auto;
  border: 1px solid red;

  .item {
    position: relative;
    padding: 10px;
    border-bottom: 1px solid #ccc;
  }
  .btn-add {
    position: absolute;
    right: 10px;
    top: 40px;
  }
}
</style>